package utils;

import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtils extends org.apache.commons.lang3.StringUtils {


    public static boolean isEmpty(@Nullable Object str) {
        return org.springframework.util.StringUtils.isEmpty(str);
    }

    public static String delHTMLTag(String htmlStr) {
        if (isNotBlank(htmlStr)) {
            String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
            String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

            Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            Matcher m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            Matcher m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签

            Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签
            return htmlStr.trim(); // 返回文本字符串
        } else {
            return null;
        }
    }

    public static boolean isEmail(String str) {
        boolean flag = false;// 定义一个boolean型的变量用来返回
        String reg = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
        if (str.matches(reg)) {// 这时java里面的方法，就是判断你传入的str是否匹配这个正则表达式，我感觉c#里面肯定有判断正则表达的方法吧
            flag = true;
        }
        return flag;
    }

    /**
     * 根据 separatorChars 分隔符提取List列表
     *
     * @param str
     * @param separatorChars
     * @return
     */
    public static List<String> extractToList(String str, String separatorChars) {
        List<String> list = new ArrayList<String>();
        if (StringUtils.isNotEmpty(str)) {
            String[] array = StringUtils.split(str, separatorChars);
            for (String item : array) {
                list.add(item);
            }
        }
        return list;
    }

    /**
     * 获取上一次请求的url 并把get请求编码转化为utf-8
     *
     * @param str
     * @param request
     * @return
     */
    public static String setEncodingUTF(String str, HttpServletRequest request) {
        try {
            String retUrl = request.getHeader("Referer");
            int flg = retUrl.indexOf(str);
            flg = flg + (str.length()) + 1;
            retUrl = retUrl.substring(flg);
            str = new String(retUrl.trim().getBytes("iso8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * @param phone
     * @return
     * @功能：判断是否是手机号码
     * @作者：chendw
     * @时间：2010-8-4 下午12:33:09
     * @版本：
     */
    public static boolean checkPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return false;
        }
        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]\\d{4,8}$");
        Matcher matcher = pattern.matcher(phone);
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    /**
     * 生成随即密码带字符
     *
     * @param pwd_len 生成的密码的总长度
     * @return 密码的字符串
     */
    public static String genRandomStr(int pwd_len) {
        // 35是因为数组是从0开始的，26个字母+10个数字
        final int maxNum = 36;
        int i; // 生成的随机数
        int count = 0; // 生成的密码的长度

        char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9'};

        // char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < pwd_len) {
            // 生成随机数，取绝对值，防止生成负数，

            i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1

            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }

        return pwd.toString();
    }

    public static boolean isNull(String str) {
        return str == null || str == "";
    }

    //在字符中插入<br/>实现当英文字母太长时换行
    public static String insertBR(String str, int length) {
        String result = "";
        int size = str.length();
        List<String> datas = new ArrayList<String>();
        for (int i = 0; i < size; ) {
            if (i + length > size) {
                length = size - i;
            }
            String temp = str.substring(i, i + length);
            i = i + length;
            datas.add(temp);
        }
        for (int i = 0; i < datas.size(); i++) {
            if (i < datas.size() - 1) {
                result = result + datas.get(i) + "<br/>";
            } else {
                result = result + datas.get(i);
            }

        }

        return result;

    }

    public static boolean isInteger(String input) {
        Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(input);
        return mer.find();
    }

    public static String JsonCharZhuanYi(String str) {
        if (StringUtils.isNotBlank(str)) {
            str = str.replaceAll("\\\\", "\\\\\\\\");
        }
        return str;
    }

    public static String HideMiddle(String str) {
        if (StringUtils.isNotBlank(str) && StringUtils.length(str) > 4) {
            StringBuffer sb = new StringBuffer(str.substring(0, 2));
            for (int i = 0; i < str.length() - 4; i++) {
                sb.append("*");
            }
            sb.append(str.substring(str.length() - 2));
            return sb.toString();
        } else {
            return str;
        }
    }

    public static String returnEmptyIfNull(String str) {
        return str == null ? "" : str;
    }

    public static String padLeft(String src, int len, char ch) {
        int diff = len - src.length();
        if (diff <= 0) {
            return src;
        }

        char[] charr = new char[len];
        System.arraycopy(src.toCharArray(), 0, charr, 0, src.length());
        for (int i = src.length(); i < len; i++) {
            charr[i] = ch;
        }
        return new String(charr);
    }

    public static String returnNewDesc(String str1, String separator, int length) {
        if (length == 0 || str1 == null || str1.length() == 0) {
            return "";
        } else {
            if (str1.length() > length) {
                str1 = str1.substring(str1.length() - length);
                int i = str1.indexOf(";");
                if (i >= 0) {
                    str1 = str1.substring(i + 1);
                }
                return str1;
            } else {
                return str1;
            }
        }
    }

    public static boolean isDistinctStringList(List<String> stringList) {
        if (stringList == null || stringList.size() == 0) {
            return false;
        } else {
            return new HashSet<>(stringList).size() != stringList.size();
        }
    }

    /**
     * @Description: 生成n位数字、字母组合的随机数
     * @Param: [n]
     * @return: java.lang.String
     * @Author: GYY
     * @Date: 2019/7/18
     */
    public static String getRandomNumAndChar(int n) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            String str = random.nextInt(2) % 2 == 0 ? "num" : "char";
            if ("char".equalsIgnoreCase(str)) { // 产生字母
                int nextInt = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (nextInt + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(str)) { // 产生数字
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * @Description: 18位身份证号加*
     * @Param: [bindIdentityId]
     * @return: java.lang.String
     * @Author: GYY
     * @Date: 2019/8/7
     */
    public static String getSecretIdentityId18(String bindIdentityId) {
        bindIdentityId = bindIdentityId.substring(0, 6) + "********" + bindIdentityId.substring(14, 18);
        return bindIdentityId;
    }

    public static String getSecretIdentityIdFor15(String bindIdentityId) {
        bindIdentityId = bindIdentityId.substring(0, 6) + "******" + bindIdentityId.substring(12, 15);
        return bindIdentityId;
    }

    public static String getSecretIdentityId(String bindIdentityId) {
        if (StringUtils.isBlank(bindIdentityId)) {
            return "";
        }
        if (bindIdentityId.length() == 15) {
            return getSecretIdentityIdFor15(bindIdentityId);
        }
        if (bindIdentityId.length() == 18) {
            return getSecretIdentityId18(bindIdentityId);
        }
        return "";
    }

    /**
     * 对证件号进行加密处理
     *
     * @param idCardNo
     * @return
     */
    public static String getSecretIdCardNo(String idCardNo) {
        if (isBlank(idCardNo)) {
            return "";
        }
        if (idCardNo.contains("#")) {
            String[] idArray = idCardNo.split("#");
            idCardNo = idArray[0];
        }

        if (IdCardUtil.isIDNumber(idCardNo)) {
            if (idCardNo.length() == 18) {
                idCardNo = idCardNo.substring(0, 6) + "********" + idCardNo.substring(14, 18);
            } else if (idCardNo.length() == 15) {
                idCardNo = idCardNo.substring(0, 6) + "******" + idCardNo.substring(12, 15);
            }
        } else {
            String s = "*****";
            if (idCardNo.length() < 11 && idCardNo.length() > 8) {
                s = "***";
            } else if (idCardNo.length() < 9) {
                s = "**";
            }
            idCardNo = idCardNo.substring(0, 3) + s + idCardNo.substring(idCardNo.length() - 3, idCardNo.length());
        }

        return idCardNo;
    }

    /**
     * 对证件号进行加密处理 前4后4
     *
     * @param idCardNo
     * @return
     */
    public static String getSecretIdCardNo4(String idCardNo) {
        if (isBlank(idCardNo)) {
            return "";
        }
        if (idCardNo.contains("#")) {
            String[] idArray = idCardNo.split("#");
            idCardNo = idArray[0];
        }

        if (IdCardUtil.isIDNumber(idCardNo)) {
            if (idCardNo.length() == 18) {
                idCardNo = idCardNo.substring(0, 4) + "**********" + idCardNo.substring(14, 18);
            } else if (idCardNo.length() == 15) {
                idCardNo = idCardNo.substring(0, 4) + "********" + idCardNo.substring(12, 15);
            }
        } else {
            String s = "*****";
            if (idCardNo.length() < 11 && idCardNo.length() > 8) {
                s = "***";
            } else if (idCardNo.length() < 9) {
                s = "**";
            }
            idCardNo = idCardNo.substring(0, 3) + s + idCardNo.substring(idCardNo.length() - 3, idCardNo.length());
        }

        return idCardNo;
    }

    /**
     * @Description: 电话号加*
     * @Param: [mobileNumber]
     * @return: java.lang.String
     * @Author: GYY
     * @Date: 2019/8/7
     */
    public static String getSecretMobileNumber(String mobileNumber) {
        if (StringUtils.isBlank(mobileNumber)) {
            return "";
        }
        mobileNumber = mobileNumber.substring(0, 3) + "****" + mobileNumber.substring(7, 11);
        return mobileNumber;
    }

    /**
     * @return boolean
     * @Description 姓名只能输入汉字和符号·
     * @Param [args]
     */
    public static boolean nameVerification(String name) {
        String regex = "^[\u4E00-\u9FFF.·˙·]+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(name);
        return matcher.matches();
    }

}
